package com.huacai.blog.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.huacai.common.utils.DateUtils;
import com.huacai.common.utils.uuid.IdUtils;
import com.huacai.collect.service.ICollectService;
import com.huacai.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huacai.blog.mapper.BlogMapper;
import com.huacai.blog.domain.Blog;
import com.huacai.blog.service.IBlogService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;

import static com.huacai.common.utils.SecurityUtils.getUserId;

/**
 * 博客Service业务层处理
 *
 * @author lundao
 * @date 2025-09-12
 */
@Service
public class BlogServiceImpl implements IBlogService
{
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private ICollectService collectService;
    @Autowired
    private ICommentService commentService;
    private ICollectService collectMapper;
    private ICommentService commentMapper;
    private Collectors Collectors;


    /**
     * 查询博客
     *
     * @param blogId 博客主键
     * @return 博客
     */
    @Override
    public Blog selectBlogByBlogId(String blogId)
    {
        return blogMapper.selectBlogByBlogId(blogId);
    }

    /**
     * 查询博客列表
     *
     * @param blog 博客
     * @return 博客
     */


    /**
     * 查询博客列表
     *
     * @param blog 博客
     * @return 博客
     */
    @Override
    public List<Blog> selectBlogList(Blog blog) {
        //1.查询博客列表
        List<Blog> blogs = blogMapper.selectBlogList(blog);
        //2.批量获取收藏数(只有有数据的时候才处理)
        if (!blogs.isEmpty()) {
            //收集所有博客ID
            List<String> blogIds = blogs.stream()
                    .map(Blog::getBlogId)
                    .collect(Collectors.toList());
            //批量查询收藏数
            Map<String, Integer> collectCountMap = collectService.batchSelectCollectCount(blogIds);
            //批量查询评论数
            Map<String, Integer> commentCountMap = commentService.batchSelectCommentCount(blogIds);
            //设置收藏数到博客对象
            blogs.forEach(blogList ->
                    blogList.setCollectCount(collectCountMap.getOrDefault(blogList.getBlogId(), 0)));
            //设置评论数到博客对象
            blogs.forEach(blogList ->
                    blogList.setCommentCount(commentCountMap.getOrDefault(blogList.getBlogId(), 0)));
        }
        return blogs;
    }
    /**
     * 新增博客
     *
     * @param blog 博客
     * @return 结果
     */
    @Override
    public int insertBlog(Blog blog)
    {
        blog.setCreateTime(DateUtils.getNowDate());
        blog.setBlogId(IdUtils.randomUUID());
        blog.setUserId(Math.toIntExact(getUserId()));
        return blogMapper.insertBlog(blog);
    }

    /**
     * 批量新增博客
     *
     * @param blogs 博客List
     * @return 结果
     */
    @Override
    public int batchInsertBlog(List<Blog> blogs)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(blogs)) {
            try {
                for (int i = 0; i < blogs.size(); i++) {
                    int row = blogMapper.insertBlog(blogs.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == blogs.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改博客
     *
     * @param blog 博客
     * @return 结果
     */
    @Override
    public int updateBlog(Blog blog)
    {
        return blogMapper.updateBlog(blog);
    }

    /**
     * 批量删除博客
     *
     * @param blogIds 需要删除的博客主键
     * @return 结果
     */
    @Override
    public int deleteBlogByBlogIds(String[] blogIds)
    {
        return blogMapper.deleteBlogByBlogIds(blogIds);
    }

    /**
     * 删除博客信息
     *
     * @param blogId 博客主键
     * @return 结果
     */
    @Override
    public int deleteBlogByBlogId(String blogId)
    {
        return blogMapper.deleteBlogByBlogId(blogId);
    }


}
